package com.hualian.coupon.controller;

import com.hualian.coupon.exception.BusinessException;
import com.hualian.coupon.util.ResultCode;
import com.hualian.coupon.util.ResultV0;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Lxd
 * @Description TODO 全局异常处理类
 * @date 2020/10/21 1:59
 * @Version 1.0
 */
@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultV0<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        //从异常对象中拿到objectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        //提取错误信息返回
        return new ResultV0<>(ResultCode.VALIDATE_FAILED,objectError.getDefaultMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResultV0<String> BusinessExceptionHandler(BusinessException e) {
        return new ResultV0<>(ResultCode.FAILED,e.getMsg());
    }
}
